import json
from signal import raise_signal
import time
import threading
from flask import current_app, g, make_response
import requests

from app.libs.exception import APIException


class Pager():
    def __init__(self, offset: int, limit: int) -> None:
        self.offset = offset or 0
        self.limit = limit if limit is not None and limit > 0 else current_app.config[
            'PAGER_LIMIT']


def setTimeout(func, secs):
    def temp(func, secs):
        time.sleep(secs)
        func()
    threading.Thread(target=temp, args=(func, secs)).start()


class HttpHelper:

    @classmethod
    def post(cls, url, params, **kwargs):
        if not isinstance(params, dict):
            params = params.__dict__
        # params = json.dumps(params, default=lambda o: o.__dict__)
        resp = requests.post(
            url=f"{current_app.config['REMOTE_BASE_URL']}{url}",
            data=params,
            headers={'token': g.token},
            **kwargs)
        if not f'{resp.status_code}'.startswith('2'):
            raise cls.resp2APIException(resp)
        resp.content_object = json.loads(resp.content)
        return resp

    @staticmethod
    def resp2APIException(resp):
        content = json.loads(resp.content)
        return APIException(
            msg=content['msg'], code=resp.status_code, headers=resp.headers,
            error_code=content['error_code'])
